<script setup>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'

import { ref, watch } from 'vue';

const arr = JSON.parse(localStorage.getItem('todos')) || [
    { id: 1, name: '吃饭', done: true, },
    { id: 2, name: '睡觉', done: true, },
    { id: 3, name: '敲代码', done: false, },
]

const list = ref(arr)

const changeDone = (id) => {
    const obj = list.value.find(v => v.id === id)
    obj.done = !obj.done
}

const del = (id) => {
    // 写法1，过滤的方法
    // list.value = list.value.filter(v => v.id !== id)

    // 遍历数组，把符合条件的下标 返回出来
    const index = list.value.findIndex(v => v.id === id)
    console.log('index', index);
    list.value.splice(index, 1)
}
const add = (val) => {
    console.log('val', val);
    // push添加到数组最后以为，unshift 添加到数组第一位
    list.value.unshift(
        { id: +new Date(), name: val, done: false, }
    )
}

// 全选/反选，跟着打个传过来的数据走就可以了
const changeAll = (bl) => {
    list.value.forEach(v => v.done = bl)
}

watch(list.value, (val) => {
    localStorage.setItem("todos", JSON.stringify(val))
}, { deep: true })

</script>

<template>
    <section class="todoapp">
        <TodoHeader @add="add"></TodoHeader>
        <TodoMain :list="list" @changeDone="changeDone" @del="del" @changeAll="changeAll"></TodoMain>
        <TodoFooter :list="list"></TodoFooter>
    </section>
</template>

<style>
</style>
